<template>
    <div class="zs-table-page-container">
        <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
            <span>
                <el-select v-model="projectZylyCode" filterable class="zs-select-md zs-space-right-sm" placeholder="项目名称"
                    @change="changeProject()">
                    <el-option v-for="item in projectList" :key="item.projectZylyCode" :label="item.projectName"
                        :value="item.projectZylyCode" />
                </el-select>
                <el-date-picker class="zs-space-right-sm" v-model="startDateSelect" :type="pickerDate" placeholder="开始日期"
                    :clearable="false" :value-format="valueFormat" :disabled-date="disabledDateStart"
                    @change="changeDate()" />
                <el-date-picker class="zs-space-right-sm" v-model="endDateSelect" :type="pickerDate" placeholder="结束日期"
                    :clearable="false" :value-format="valueFormat" :disabled-date="disabledDateEnd"
                    @change="changeDate()" />
                <el-button class="zs-btn-plain" @click="getData()">
                    查询
                </el-button>
            </span>
            <span class="zs-layout-flex-row">
                <div class="db-btn zs-space-right-sm" :class="{ 'db-btn-primary': curTab == '日' }" @click="changeTab('日')">
                    按日
                </div>
                <div class="db-btn zs-space-right-sm" :class="{ 'db-btn-primary': curTab == '月' }" @click="changeTab('月')">
                    按月
                </div>
                <div class="db-btn zs-space-right" :class="{ 'db-btn-primary': curTab == '年' }" @click="changeTab('年')">按年
                </div>
                <el-button class="zs-btn-plain" @click="handleDownload" disabled><el-icon class="el-icon--left">
                        <Upload />
                    </el-icon>导出</el-button>
            </span>
        </div>
        <div class="zs-card zs-table-page-content">
            <el-table :data="tableData" class="zs-table-page-main" :stripe="stripe">
                <el-table-column label="序号" width="60" :align="'center'">
                    <template #default="scope">
                        {{ scope.$index + 1 + curPageSize * (currentPage - 1) }}
                    </template>
                </el-table-column>
                <el-table-column prop="timeDate" label="日期" width="120" :align="'center'"></el-table-column>
                <el-table-column label="进货成本" :align="'right'">
                    <template #default="scope">
                        {{ toThousands(scope.row.purchaseCostThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="销货成本" :align="'right'">
                    <template #default="scope">
                        {{ toThousands(scope.row.salesCostThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="其他成本" :align="'right'">
                    <template #default="scope">
                        {{ toThousands(scope.row.otherCostsThousand) }}
                    </template>
                </el-table-column>

                <el-table-column label="存货成本" :align="'right'" v-if="curTab == '日'">
                    <template #default="scope">
                        {{ toThousands(scope.row.avgAnnualSalesThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="存货预警值" :align="'right'" v-if="curTab == '日'">
                    <template #default="scope">
                        {{ toThousands(scope.row.inventoryAlertValueThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="存货预警" :align="'right'" v-if="curTab == '日'">
                    <template #header>
                        <div class="zs-layout-flex-row zs-layout-items-center zs-layout-justify-end">
                            <div>存货预警</div>
                            <el-popover placement="bottom" :width="300" trigger="hover" content="（当前存货-存货预警值）/存货预警值">
                                <template #reference>
                                    <i class="icon-i zs-text-gray zs-space-left-min"></i>
                                </template>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        {{ toThousands(scope.row.inventoryAlertThousand) }}
                    </template>
                </el-table-column>

                <el-table-column label="累计进货（月）" :align="'right'" v-if="curTab == '月'">
                    <template #default="scope">
                        {{ toThousands(scope.row.inventoryAlertValueThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="累计销货（月）" :align="'right'" v-if="curTab == '月'">
                    <template #default="scope">
                        {{ toThousands(scope.row.inventoryAlertThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="日均存货（月）" :align="'right'" width="140" v-if="curTab == '月'">
                    <template #header>
                        <div class="zs-layout-flex-row zs-layout-items-center zs-layout-justify-end">
                            <div>日均存货（月）</div>
                            <el-popover placement="bottom" :width="300" trigger="hover" content="当月累计每日库存/当月天数">
                                <template #reference>
                                    <i class="icon-i zs-text-gray zs-space-left-min"></i>
                                </template>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        {{ toThousands(scope.row.avgAnnualSalesThousand) }}
                    </template>
                </el-table-column>

                <el-table-column label="累计进货（年）" :align="'right'" v-if="curTab == '年'">
                    <template #default="scope">
                        {{ toThousands(scope.row.inventoryAlertValueThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="累计销货（年）" :align="'right'" v-if="curTab == '年'">
                    <template #default="scope">
                        {{ toThousands(scope.row.inventoryAlertThousand) }}
                    </template>
                </el-table-column>
                <el-table-column label="日均存货（年）" :align="'right'" width="140" v-if="curTab == '年'">
                    <template #header>
                        <div class="zs-layout-flex-row zs-layout-items-center zs-layout-justify-end">
                            <div>日均存货（年）</div>
                            <el-popover placement="bottom" :width="300" trigger="hover" content="当年累计每日库存/当年天数">
                                <template #reference>
                                    <i class="icon-i zs-text-gray zs-space-left-min"></i>
                                </template>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        {{ toThousands(scope.row.avgAnnualSalesThousand) }}
                    </template>
                </el-table-column>


                <el-table-column prop="" label="操作" width="100" :align="'right'">
                    <template #default="scope">
                        <el-button class="zs-link" link size="small" @click="goDetail(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTab == '日'">*进货成本，销货成本，存货成本，存货预警值：万元</div>
            <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTab == '月'">
                *进货成本，销货成本，累计进货（月），累计销货（月），日均存货（月）：万元</div>
            <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTab == '年'">
                *进货成本，销货成本，累计进货（年），累计销货（年），日均存货（年）：万元</div>
            <div class="zs-space-top-sm zs-table-page-pagination">
                <el-pagination v-model:currentPage="currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes"
                    :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
    </div>
</template>
<script setup>
import dbPublicApi from '@/api/dbPublic'
import detailApi from '@/api/SelfSupport/detailPages'
import { ElMessage } from 'element-plus'
import { dateFormat, toThousands } from '@/utils/number-util'
import { downloadNewFile } from "@/utils/publicUtils"
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
let store = useStore()
const stripe = ref(true)
const route = useRoute().query

let projectZylyCode = ref(route.projectZylyCode)
let projectName = ref('')
const updateDate = route.updateDate
const tabPermi = route.tabPermi
let curTab = ref(route.curTab)
let startDate = ref('') // 进入页面时的 开始日期
let endDate = ref('') // 进入页面时的 结束日期
let startDateSelect = ref('') // 筛选项 开始日期
let endDateSelect = ref('') // 筛选项 结束日期
let valueFormat = ref('YYYY-MM-DD')
let pickerDate = ref('date')

let projectList = ref([])
const getPorjectList = async () => {
    await dbPublicApi.queryProjectPcApi({ dataTime: updateDate, resourceKey: tabPermi }).then((res) => {
        if (res.data.code == 200) {
            projectList.value = res.data.data
            const project = projectList.value.find(item => {
                return item.projectZylyCode == projectZylyCode.value
            })
            projectName.value = project.projectName
        }
    })
}

const changeProject = () => {
    const project = projectList.value.find(item => {
        return item.projectZylyCode == projectZylyCode.value
    })
    projectName.value = project.projectName
}

const changeTab = (value) => {
    curTab.value = value
    init()
}



const curPageSizes = ref(store.state.uiPageSizes)
let curPageSize = ref(store.state.uiPageSizeDefault)
// 分页
let currentPage = ref(1)
const total = ref(0)
const handleSizeChange = (val) => {
    curPageSize.value = val
    getList()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getList()
}

const tableData = ref([])
// 未选择日期组件时，使用url参数查询，选择了日期之后，使用页面选择的日期（ps: 为了默认进来显示出【开始日期】【结束日期】）
const isSelect = ref(false)
const changeDate = () => {
    isSelect.value = true
}
const getList = () => {
    if (isSelect.value && ((startDateSelect.value && !endDateSelect.value) || (!startDateSelect.value && endDateSelect.value))) {
        ElMessage({
            message: '请选择开始日期和结束日期',
            type: 'warning',
        })
        return false
    }
    let start = isSelect.value ? startDateSelect.value : startDate.value
    let end = isSelect.value ? endDateSelect.value : endDate.value
    detailApi.queryEntireApi({ projectName: projectName.value, startDate: start, endDate: end, timeType: curTab.value, pageNo: currentPage.value, pageSize: curPageSize.value }).then((res) => {
        if (res.data.code == 200) {
            tableData.value = res.data.data.data
            total.value = res.data.data.totalCount
        }
    })
}
const getData = () => {
    currentPage.value = 1
    getList()
}

const handleDownload = async () => {
    const fileName = `整场${curTab.value}列表.xls`
    let fileData
    await detailApi.saleSceneExportApi({ projectZylyCode: projectZylyCode.value, startDate: startDate.value, endDate: endDate.value, timeType: curTab.value }).then(res => {
        fileData = res.data
    })
    downloadNewFile(fileData, fileName)
}


const goDetail = (row) => {
    router.push({
        path: '/page/routeController/index',
        query: {
            rid: 'SelfSupport/detailPages/inventoryManagement/wholeSceneBrand',
            rTitle: '整场品牌',
            projectZylyCode: projectZylyCode.value,
            projectName: projectName.value,
            dataTime: row.timeDate,
            updateDate: updateDate,
            tabPermi: tabPermi,
            curTab: curTab.value,
        },
    })
}

const disabledDateStart = (date) => {
    return date.getTime() < new Date('2019-05-01').getTime() - 24 * 60 * 60 * 1000 || date.getTime() > new Date(updateDate).getTime()
}

const disabledDateEnd = (date) => {
    return date.getTime() < new Date('2019-05-01').getTime() - 24 * 60 * 60 * 1000 || date.getTime() > new Date(updateDate).getTime()
}

const init = async () => {
    if (curTab.value == '日') {
        pickerDate.value = 'date'
        valueFormat.value = 'YYYY-MM-DD'

        startDate.value = dateFormat(new Date(new Date(updateDate).getTime() - 30 * 24 * 60 * 60 * 1000), 'YYYY-MM-DD')
        endDate.value = updateDate

        if (new Date(startDate.value).getTime() < new Date('2019-05-01').getTime()) {
            startDate.value = '2019-05-01'
        }
    }
    if (curTab.value == '月') {
        pickerDate.value = 'month'
        valueFormat.value = 'YYYY-MM'

        // 先将月份+1 再将年份-2 获取近24个月 如（2021-10到2023-9）
        let data = new Date(updateDate)
        data.setMonth(data.getMonth() + 1)
        data.setFullYear((data.getFullYear() - 2))
        startDate.value = dateFormat(data, 'YYYY-MM')
        endDate.value = dateFormat(new Date(updateDate), 'YYYY-MM')

        if (new Date(startDate.value).getTime() < new Date('2019-05').getTime()) {
            startDate.value = '2019-05'
        }
    }
    if (curTab.value == '年') {
        pickerDate.value = 'year'
        valueFormat.value = 'YYYY'

        const year = new Date(updateDate).getFullYear() - 20
        startDate.value = year.toString()
        endDate.value = new Date(updateDate).getFullYear().toString()

        if (new Date(startDate.value).getTime() < new Date('2019').getTime()) {
            startDate.value = '2019'
        }
    }
    if (isSelect.value) {
        startDateSelect.value = isSelect.value ? startDate.value : ''
        endDateSelect.value = isSelect.value ? endDate.value : ''
    }
    await getPorjectList()
    getData()
}
init()
</script>


<style scoped lang="scss"></style>
